#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : chat_model 
# @File    : knowledge_logic.py
# @IDE     : PyCharm 
# @Author  :ZH
# @Time    : 2025/1/10 16:17
__all__ = ['knowledge_logic']

from tortoise.expressions import Q

from apps import cruds
from apps.api.v1.knowledge_api.schema import KnowledgeListRequests
from apps.models import User


class KnowledgeLogic:
    def __init__(self):
        self.crud = cruds.knowledge_crud

    async def knowledge_list(self, query: KnowledgeListRequests, user: User):
        skip = (query.page - 1) * query.limit
        query_sql = self.crud.model.filter(is_delete=False, user_id=user.id)
        if query.name:
            query_sql = query_sql.filter(knowledge_name__icontains=query.name)
        count_ = await query_sql.count()
        if count_:
            data = await query_sql.order_by('-id').offset(skip).limit(query.limit).all()
        else:
            data = []
        return count_, data

    async def knowledge_create(
            self, knowledge_name: str, embedding_server_id: int, user: User, description: str = None
    ):
        return await self.crud.create(obj_in={
            'knowledge_name': knowledge_name,
            'embedding_server_id': embedding_server_id,
            'user_id': user.id,
            'description': description,
            # 'file_extract_id': file_extract_id
        })

    async def knowledge_object(self, knowledge_id: int, user: User):
        return await self.crud.get_one(
            is_delete=False, id=knowledge_id, user_id=user.id
        )

    async def all_knowledge_object(self, **kwargs):
        return await self.crud.get_all(**kwargs)


knowledge_logic = KnowledgeLogic()
